<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
      style="flex-wrap: wrap;padding: 10px;box-sizing: border-box;height: unset;display: flex;">
      <el-form-item prop="plotId" label="所属小区：">
        <el-select v-model="queryParams.plotId" placeholder="请选择小区名称" clearable @change="xiaoquChange">
          <el-option v-for="dict in xiaoquData" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item prop="buildId" label="所属楼栋：">
        <el-select v-model="queryParams.buildId" placeholder="请选择楼栋" clearable style="width: 170px;"
          @change="loudonChange">
          <el-option v-for="dict in loudongData" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item prop="unitId" v-if="listNum === 1 || listNum === 2" label="所属单元：">
        <el-select v-model="queryParams.unitId" placeholder="请选择单元" clearable style="width: 200px" @change="$forceUpdate()">
          <el-option v-for="dict in danyuanData" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="类型：" prop="selectType">
        <el-select v-model="queryParams.selectType" placeholder="请选择类型">
          <el-option v-for="item in selectTypeList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item prop="houseId" v-if="listNum === 2" label="所属房号：">
        <el-input v-model="queryParams.houseNumber" placeholder="请输入房号" clearable />
      </el-form-item>
      <el-form-item label="数据时间：">
        <el-date-picker value-format="yyyy-MM-dd" v-model="dateRange" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期" align="right">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="数据展示类型：">
        <el-select @change="tableShowChange" multiple collapse-tags v-model="tableActiveList" placeholder="请选择需展示数据">
          <el-option v-for="item in tableSelectList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="primary" icon="el-icon-download" @click="handleExport">导出</el-button>
      </el-form-item>

    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="2.5">
        <el-button :class="listNum === 0 ? 'active' : 'unactive'" type="primary" @click="checkList(0)">楼栋列表</el-button>
      </el-col>
      <el-col :span="2.5">
        <el-button :class="listNum === 1 ? 'active' : 'unactive'" autofocus type="primary"
          @click="checkList(1)">单元列表</el-button>
      </el-col>
      <el-col :span="2.5">
        <el-button :class="listNum === 2 ? 'active' : 'unactive'" type="primary" @click="checkList(2)">住户列表</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table @sort-change="tableSortChange" v-loading="loading" :data="typeList">
      <el-table-column show-overflow-tooltip label="序号" align="center" type="index"></el-table-column>

      <!-- <el-table-column :key="item.value" v-for="item in tableShowList" show-overflow-tooltip :label="item.label"
        align="center" :prop="item.value" :sortable="item.sortable">
          <template slot="header" slot-scope="scope">
          <span>
            {{item.label}}
          </span>
            <el-select v-model="checkedUnit" placeholder="单位" size="mini" class="unitSelect" v-if="item.unitSwitch">
              <el-option
                :key="1"
                label="度"
                value="1">
              </el-option>
              <el-option
                :key="2"
                label="摄氏度"
                value="2">
              </el-option>
            </el-select>
        </template>
        <template slot-scope="scope">
          <span v-if="item.value=='waterSupplyTemperature'">{{waterSupplyTemperature(scope.row[item.value],checkedUnit)}}</span>
          <span v-else>{{scope.row[item.value]}}</span>
        </template>
      </el-table-column> -->
      <el-table-column :key="item.value" v-for="item in tableShowList" show-overflow-tooltip :label="item.label"
        align="center" :prop="item.value" :sortable="item.sortable">
        <template slot-scope="scope">
          <span v-if="item.value == 'velocityFlow'">{{convertVelocityFlow(scope.row[item.value])}}</span>
          <span v-else-if="item.value == 'totalFlow'">{{convertTotalFlow(scope.row[item.value])}}</span>
          <span v-else-if="item.value == 'thermalPower'">{{convertThermalPower(scope.row[item.value])}}</span>
          <span v-else-if="item.value == 'currentHeatOrCold'">{{convertCurrentHeatOrCold(scope.row[item.value])}}</span>
          <span v-else-if="item.value == 'waterSupplyTemperature'">{{scope.row[item.value]+" ℃"}}</span>
          <span v-else-if="item.value == 'returnWaterTemperature'">{{scope.row[item.value]+" ℃"}}</span>
          <span v-else-if="item.value == 'roomTemperature'">{{scope.row[item.value]+" ℃"}}</span>
          <span v-else>{{scope.row[item.value]}}</span>
        </template>
      </el-table-column>
      <!--       
      <el-table-column show-overflow-tooltip label="序号" align="center" type="index"></el-table-column>
      <el-table-column show-overflow-tooltip label="所属小区名称" align="center" prop="plotName" />
      <el-table-column show-overflow-tooltip label="楼栋" align="center" prop="buildName" />
      <el-table-column show-overflow-tooltip v-if="listNum !== 0" label="单元" align="center" prop="unitName" />
      <el-table-column show-overflow-tooltip v-if="listNum !== 1 && listNum !== 0" label="楼层" align="center"
        prop="floor" />
      <el-table-column show-overflow-tooltip v-if="listNum !== 1 && listNum !== 0" label="户号" align="center"
        prop="houseNumber" />
      <el-table-column show-overflow-tooltip label="瞬时热量" align="center" prop="thermalPower"></el-table-column>
      <el-table-column show-overflow-tooltip label="瞬时流量" align="center" prop="velocityFlow"></el-table-column>
      <el-table-column show-overflow-tooltip label="供水温度" align="center" prop="waterSupplyTemperature" />
      <el-table-column show-overflow-tooltip label="回水温度" align="center" prop="returnWaterTemperature"></el-table-column>
      <el-table-column show-overflow-tooltip label="累计流量" align="center" prop="totalFlow"></el-table-column>
      <el-table-column show-overflow-tooltip label="累计热量" align="center" prop="currentHeatOrCold"></el-table-column>
      <el-table-column show-overflow-tooltip label="阀门开度" align="center" prop="setOpen"></el-table-column>
      <el-table-column show-overflow-tooltip width="120px" label="阀门表抄表时间" align="center"
        prop="valveCrateTime"></el-table-column>
      <el-table-column show-overflow-tooltip width="120px" label="热量表抄表时间" align="center"
        prop="thermalCreateTime"></el-table-column>
      <el-table-column show-overflow-tooltip v-if="listNum !== 1 && listNum !== 0" label="室温" align="center"
        prop="roomTemperature"></el-table-column>
      <el-table-column show-overflow-tooltip width="120px" v-if="listNum !== 1 && listNum !== 0" label="室温抄表时间"
        align="center" prop="roomCrateTime"></el-table-column> -->


      <!-- <el-table-column align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column> -->
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
  </div>
</template>

<script>
import {
  listBuildUnit, listHousehold, listBuildExport, listBuildUnitExport,
  listHouseholdExport, listBuild, listAvgBuildUnit, listAvgHousehold, listAvgBuild,
} from '@/api/system/data.js'
import { listCPlotNoPage } from '@/api/system/utils.js'
import { listCPlotSelect, listBuildSelect, listBuildUnitSelect } from "@/api/system/utils"
import { fieldList, fieldInsert } from "@/api/system/field"
// import { dataList } from "@/api/mock"
// import data5 from "@/utils/data5.json"
export default {
  name: "Dict",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      selectTypeList: [
        { label: "热量表", value: 1 },
        { label: "阀门", value: 2 },
        { label: "室温采集器", value: 3 },
      ],
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 小区名字
      xiaoquData: [],
      loudongData: [],
      danyuanData: [],
      houseData: [],
      listNum: 0,
      // 字典表格数据
      typeList: [],
      // 日期范围
      dateRange: [],
      // 展示类型
      typeValue: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        startTime: null,
        endTime: null,
        buildId: null,
        plotId: null,
        unitId: null,
        houseNumber: null,
        selectType: 1,
      },
      unitsName:[],
      checkedUnit:"1",
      tableAllSelectlist: [
        {
          label: '所属小区名称',
          value: 'plotName',
        },
        {
          label: '楼栋',
          value: 'buildName',
        },
        {
          label: '单元',
          value: 'unitName',
        },
        {
          label: '楼层',
          value: 'floor',
        },
        {
          label: '户号',
          value: 'houseNumber',
        },
        {
          label: '瞬时热量',
          value: 'thermalPower',
        },
        {
          label: '瞬时流量',
          value: 'velocityFlow',
        },
        {
          label: '供水温度',
          value: 'waterSupplyTemperature',
          unitSwitch:true
        },
        {
          label: '回水温度',
          value: 'returnWaterTemperature',
        },
        {
          label: '累计流量',
          value: 'totalFlow',
        },
        {
          label: '累计热量',
          value: 'currentHeatOrCold',
        },
        {
          label: '热量表抄表时间',
          value: 'thermalCreateTime',
        },
        {
          label: '阀门开度',
          value: 'setOpen',
          sortable: true,
        },
        {
          label: '阀门表抄表时间',
          value: 'valveCrateTime',
        },
        {
          label: '室温',
          value: 'roomTemperature',
        },
        {
          label: '室温抄表时间',
          value: 'roomCrateTime',
        },
      ],
      // 保存每条列表展示字段
      tableActiveList: [],
      // tableValue:[],
      selectType:1, //搜索选择类型，搜索后改变列表
    };
  },
  watch:{
    checkedUnit(newValue, oldValue){
        console.log(oldValue)
        console.log(newValue)
      }
  },
  computed: {
    // 计算没条列表下每个类型的字段的value
    // tableValueList() {
    //   let arr = []
    //   for (let i = 0; i < this.tableActiveList.length; i++) {
    //     let index = this.tableSelectList.findIndex(item => item.value == this.tableActiveList[i])
    //     if (index != -1) {
    //       arr.push(this.tableActiveList[i])
    //     }
    //   }
    //   return arr
    // },

    // 计算数据展示选择项
    tableSelectList() {
      // 排除列表项没有的字段
      let excludeList
      if (this.listNum == 0) {
        excludeList = ['unitName', 'floor', 'houseNumber', 'roomTemperature', 'roomCrateTime']
      } else if (this.listNum == 1) {
        excludeList = ['floor', 'houseNumber']
      } else if (this.listNum == 2) {
        excludeList = []
      }
      //排除选择类型没有的字段
        if (this.selectType == 1) {
        excludeList = excludeList.concat(['setOpen', 'valveCrateTime', 'roomTemperature', 'roomCrateTime',])
      } else if (this.selectType == 2) {
        excludeList = excludeList.concat(['thermalPower', 'waterSupplyTemperature', 'returnWaterTemperature',
          'currentHeatOrCold', 'thermalCreateTime', 'roomTemperature', 'roomCrateTime', 'velocityFlow', 'totalFlow'])
      } else if (this.selectType == 3) {
        excludeList = excludeList.concat(['setOpen', 'valveCrateTime', 'thermalPower', 'waterSupplyTemperature',
          'returnWaterTemperature', 'currentHeatOrCold', 'thermalCreateTime', 'velocityFlow', 'totalFlow'])
      } 
      return this.tableAllSelectlist.filter(item => {
        return !excludeList.includes(item.value)
      })
    },
    // 计算展示列表
    tableShowList() {
      return this.tableSelectList.filter(item => {
        return this.tableActiveList.includes(item.value)
      })
    },
  },
  created() {
    if (this.$route.query.type) {
      let { type, plotId, buildId, unitId, houseNumber } = this.$route.query
      console.log(plotId)
      this.listNum = Number(type)
      this.queryParams.plotId = plotId
      this.queryParams.buildId = buildId
      this.queryParams.unitId = unitId
      this.queryParams.houseNumber = houseNumber
      listBuildSelect({ plotId }).then(res => {
        this.loudongData = res.rows
      }, err => {
        this.$message.error('获取楼栋列表失败')
      })
      listBuildUnitSelect({ buildId }).then(res => {
        this.danyuanData = res.rows
      }, err => {
        this.$message.error('获取单元列表失败')
      })
    } else if (this.$route.query.houseNumber) {
      this.queryParams.houseNumber = this.$route.query.houseNumber
      this.listNum = 2
    }
    this.getFieldList()
    listCPlotSelect({}).then(res => {
      this.xiaoquData = res.rows
      if(!this.$route.query.type){
        this.queryParams.plotId = res.rows[0].value
      }
      listBuildSelect({ plotId:res.rows[0].value }).then(res => {
        this.loudongData = res.rows
      }, err => {
        this.$message.error('获取楼栋列表失败')
      })
    }).then(res=>{
      this.getList();
    });
    
  },
  methods: {
    // 获取展示字段列表
    getFieldList() {
      let model = 1
      let businessType = this.listNum + 1
      fieldList({ model, businessType }).then(res => {
        if (res.rows.length > 0) {
          this.tableActiveList = res.rows.map(item => item.fieldName)
        } else {
          this.tableActiveList = this.tableSelectList.map(item => item.value)
        }
      })
    },
    xiaoquChange(value) {
      if (value) {
        listBuildSelect({ plotId: this.queryParams.plotId }).then(res => {
          this.queryParams.buildId = null;
          this.queryParams.unitId = null;
          this.loudongData = res.rows
          this.danyuanData = []
        });
      } else {
        this.queryParams.buildId = null;
        this.queryParams.unitId = null;
        this.loudongData = []
        this.danyuanData = []
      }
    },
    loudonChange(value) {
      this.$forceUpdate()
      if (value) {
        listBuildUnitSelect({ buildId: this.queryParams.buildId }).then(res => {
          this.queryParams.unitId = null;
          this.danyuanData = res.rows
        });
      } else {
        this.queryParams.unitId = null;
        this.danyuanData = []
      }
    },
    // 查询条件
    async getTiaoJian() {
      const res = await listCPlotNoPage()
      this.loudongData = res.data.buildName
      this.danyuanData = res.data.parkName
      this.xiaoquData = res.data.parkName
      console.log(res);
    },
    // 查询不同类型
    checkList(num) {
      if (num != this.listNum) {
        this.listNum = num
        // this.tableActiveList = []
        this.getFieldList()
        if (this.listNum == 0) {
          this.queryParams.unitId = null;
          this.queryParams.houseNumber = null;
        }
        if (this.listNum == 1) {
          this.queryParams.houseNumber = null;
        }
        this.typeList = []
        this.getList()
      }
    },
    /** 查询字典类型列表 */
    async getList() {
      this.loading = true;
      try {
        // const res = this.listNum === 0 ? this.typeValue === 0 ? await listBuildUnit(this.queryParams) : await listAvgBuildUnit(this.queryParams) : this.listNum === 1 ? this.typeValue === 0 ? await listHousehold(this.queryParams) : await listAvgHousehold(this.queryParams) : this.typeValue === 0 ? await listBuild(this.queryParams) : await listAvgBuild(this.queryParams)
        const res = this.listNum === 1 ? this.typeValue === 0 ? await listBuildUnit(this.queryParams) : await listAvgBuildUnit(this.queryParams) : this.listNum === 2 ? this.typeValue === 0 ? await listHousehold(this.queryParams) : await listAvgHousehold(this.queryParams) : this.typeValue === 0 ? await listBuild(this.queryParams) : await listAvgBuild(this.queryParams)
        // const res = await dataList({ ...this.queryParams, listFlag: this.listNum })
        if (res.code === 200) {
          this.typeList = res.rows;
          this.total = res.total;
          this.loading = false;
          
        }

      } catch (error) {
        this.loading = false;
      }
    },
    /** 搜索结果展示的列表 **/
    selectTable(){
      if (this.selectType == 1) {
        excludeList = excludeList.concat(['setOpen', 'valveCrateTime', 'roomTemperature', 'roomCrateTime',])
      } else if (this.selectType == 2) {
        excludeList = excludeList.concat(['thermalPower', 'waterSupplyTemperature', 'returnWaterTemperature',
          'currentHeatOrCold', 'thermalCreateTime', 'roomTemperature', 'roomCrateTime', 'velocityFlow', 'totalFlow'])
      } else if (this.selectType == 3) {
        excludeList = excludeList.concat(['setOpen', 'valveCrateTime', 'thermalPower', 'waterSupplyTemperature',
          'returnWaterTemperature', 'currentHeatOrCold', 'thermalCreateTime', 'velocityFlow', 'totalFlow'])
      } 
      return this.tableAllSelectlist.filter(item => {
        return !excludeList.includes(item.value)
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      console.log(this.dateRange);
      if (this.dateRange && this.dateRange.length !== 0) {
        this.queryParams.startTime = this.dateRange[0]
        this.queryParams.endTime = this.dateRange[1]
      } else {
        this.queryParams.startTime = null
        this.queryParams.endTime = null
      }
      this.getList();
      this.selectType = this.queryParams.selectType
      
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      
      this.queryParams = {
        pageNum:1,
        pageSize:10,
        selectType:1
      }
      this.selectType = null
      this.handleQuery();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      console.log(row);
      const dictIds = row.dictId || this.ids;
      this.$modal.confirm('是否删除该条数据？').then(function () {
        return delType(dictIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    tableShowChange(e) {
      if (e.length <= 0) {
        this.$message.warning('请至少选择一项展示')
      } else {
        console.log(e)
        let arr = e.map(item => {
          return {
            fieldName: item,
            model: 1,
            businessType: this.listNum + 1,
          }
        })
        fieldInsert(arr).then(res => {
          console.log(res)
        })
      }
    },
    tableSortChange({ column, order, prop }) {
      if (order) {
        let numMap = new Map([
          ['setOpen', 9],
        ])
        this.queryParams.fieldNumber = numMap.get(prop)
        this.queryParams.sortType = order === 'ascending' ? 'asc' : 'desc'
      } else {
        this.queryParams.sortType = null
        this.queryParams.fieldNumber = null
      }
      this.getList()
    },
    /** 导出按钮操作 */
    handleExport() {
      const res = this.listNum === 1 ?
        this.typeValue === 0 ? '/dataManagement/listBuildUnitExport' : '/dataManagement/listAvgBuildUnitExport' : this.listNum === 2 ? this.typeValue === 0 ? '/dataManagement/listHouseholdExport' : '/dataManagement/listAvgHouseholdExport' : this.typeValue === 0 ? '/dataManagement/listBuildExport' : '/dataManagement/listAvgBuildExport'
      this.download(res, {
        ...this.queryParams
      }, `type_${new Date().getTime()}.xlsx`)
    },
    //回水温度
    waterSupplyTemperature(e,checkedUnit){
      console.log(e,checkedUnit);
      if(checkedUnit=='1'){
        return e
      }
      if(checkedUnit=='2'){
        return e/100
      }
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-table .cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

::v-deep .el-table {
  background: #374056;
}

.unitSelect{
  ::v-deep .el-input{
    width: 80px !important;
  }
  ::v-deep .el-input__inner{
    width: 80px !important;

  }
}
</style>
